import React, { useMemo, useState } from "react";
import { UserApp, UserAppDetail } from "../../../serve/interface";
import { Empty, Input, Result, Tree, TreeProps } from "antd";
import { CaretDownOutlined } from "@ant-design/icons";
import { mapTreeData, searchTreeData, TreeItem } from "../../utils/mapTreeData";
import { DataNode } from "antd/es/tree";

interface PreviewTreeProps {
    selectKey: number;
    onSelectKey: (item_id: number) => void;
    detail: UserAppDetail;
    app: UserApp;
}

export function PreviewTree(props: PreviewTreeProps) {
    const { app, detail, selectKey, onSelectKey } = props;
    const [keyword, setKeyword] = useState<string>("");
    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    const toggleExpandedKeys = (key: React.Key) => {
        setExpandedKeys(expandedKeys => {
            const index = expandedKeys.indexOf(key);
            if (index === -1) {
                return [...expandedKeys, key];
            } else {
                return expandedKeys.filter(item => item !== key);
            }
        });
    }
    const treeData = useMemo(() => {
        const treeData = mapTreeData(detail?.tree, {
            key: "id",
            title: "title",
            label: "title",
            parent_key: "parentId",
            __with_pinyin__: true,
            __with_rest__: true,
        })
        const expandedKeys: React.Key[] = []
        function findFirst(node: TreeItem) {
            if (node.children?.length) {
                return findFirst(node.children?.[0])
            } else {
                return node
            }
        }
        treeData[1].forEach(item => {
            const node = item as DataNode
            const isLeaf = !node.children?.length
            if (isLeaf) {
                delete node.children;
            } else {
                expandedKeys.push(node.key)
                if (app.hideParent) {
                    node.selectable = false
                    node.title = <div onClick={() => toggleExpandedKeys(node.key)}>{item.title}</div>
                }
            }
        })
        setExpandedKeys(expandedKeys)
        if (!selectKey && treeData[0]?.length) {
            const first = findFirst(treeData[0][0])
            onSelectKey(first.key as number)
        }
        return searchTreeData(keyword, treeData)
    }, [detail, keyword, selectKey]);

    const onSelect: TreeProps["onSelect"] = (selectedKeys) => {
        const [item_id] = selectedKeys as [number];
        if (item_id) {
            onSelectKey(item_id)
        }
    };

    return <>
        <div className="p-2">
            <Input placeholder="请输入文档名称搜索"
                className="mb-2"
                onInput={(e) => setKeyword(e.currentTarget.value)}
            />
            {treeData.length === 0
                ? <Empty description="暂无数据" />
                : <Tree
                    className="overflow-auto md:max-h-[calc(100vh-120px)]"
                    selectedKeys={selectKey ? [selectKey] : []}
                    expandedKeys={expandedKeys}
                    onExpand={(expandedKeys) => setExpandedKeys(expandedKeys)}
                    draggable={{ icon: false }}
                    treeData={treeData}
                    blockNode
                    onSelect={onSelect}
                    switcherIcon={<CaretDownOutlined style={{ verticalAlign: "0.125em" }} />}
                />
            }
        </div>
    </>;
}